<template>
  <div>
    <!-- 商品(spu)介绍 -->
    <div class="box">
      <h4>商品(spu)介绍</h4>
      <!-- 内容 -->
      <el-form :inline="true" :model="addr" class="demo-ruleForm" status-icon label-width="120px" width="100%" :rules="rules" ref="addr">
        <el-form-item label="商品名称" prop="title" style="width: 100%;">
          <el-input v-model.trim="addr.title" placeholder="商品名称" />
        </el-form-item>
        <el-form-item label="原始价格" prop="originalPrice" style="width: 100%;">
          <el-input v-model.number="addr.originalPrice" placeholder="0" type="number">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="当前价格" prop="price" style="width: 100%;">
          <el-input v-model.number="addr.price" placeholder="0" type="number">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="VIP价格" prop="vipPrice" style="width: 100%;">
          <el-input v-model.number="addr.vipPrice" placeholder="0" type="number">
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="剩余库存" prop="stock" style="width: 100%;">
          <el-input v-model.trim="addr.stock" disabled />
        </el-form-item>
        <el-form-item label="运费模板" prop="freightTemplateId">
          <el-select v-model="addr.freightTemplateId" placeholder="请选择运费模板">
            <el-option v-for="item in freightOptions" :key="item.id" :label="item.title" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否在售" style="width: 100%;">
          <el-radio-group v-model="addr.status">
            <el-radio :label="1">在售</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="广告图片" prop="img" v-model="addr.img">
          <el-upload action="http://192.168.1.188:8080/upload/admin" list-type="picture-card" :on-success="handleAvatarSuccess" :headers="token" :file-list="addr.imgList">
            <!-- <img v-if="addr.img" :src="addr.img" /> -->
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品单位" prop="unit" style="width: 100%;">
          <el-input v-model.trim="addr.unit" placeholder="商品单位" />
        </el-form-item>
        <el-form-item label="所属类目" prop="categoryId" style="width: 100%;">
          <el-cascader v-model="addr.categoryId" :options="typeData" :props="props" placeholder="选择类目" clearable />
        </el-form-item>
        <el-form-item label="商品简介" prop="description" style="width: 100%;">
          <el-input v-model.trim="addr.description" />
        </el-form-item>

        <!-- 富文本框内容 -->
        <el-form-item label="商品详细介绍" prop="detail" style="width: 100%;">
          <rich-text v-model="addr.detail"></rich-text>
        </el-form-item>
      </el-form>
    </div>

    <!-- 商品参数 -->
    <div class="box">
      <h4>商品参数</h4>
      <el-button size="small" type="primary" plain @click="parameterAdd">添加</el-button>

      <!-- 表格 -->
      <el-table ref="argumentForm" :data="addr.attributeList" border style="width: 100%">
        <el-table-column label="商品参数名称" prop="attribute" align="center" />
        <el-table-column label="商品参数值" prop="value" align="center" />
        <el-table-column label="操作" fixed="right" align="center" width="180">
          <template #default="scope">
            <el-button type="primary" @click="tableEdit(scope.row) ">编辑</el-button>
            <el-button type="danger" @click="tableRemove(scope.row, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 对话框 -->
      <el-dialog v-model="dialogVisible" title="设置商品参数" width="600px" :before-close="handleClose">
        <!-- 内容 -->
        <el-form :inline="true" :model="parameterAddr" class="demo-ruleForm" status-icon label-width="120px" :rules="rules1" ref="argumentForm">
          <el-form-item label="商品参数名称" prop="attribute">
            <el-input v-model.trim="parameterAddr.attribute" placeholder="商品参数名称" />
          </el-form-item>
          <el-form-item label="商品参数值" prop="value">
            <el-input v-model.trim="parameterAddr.value" placeholder="商品参数值" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="parameterNew() ">确认</el-button>
        </template>
      </el-dialog>

      <!-- 编辑对话框 -->
      <el-dialog v-model="EditVisible" title="编辑商品参数" width="600px" :before-close="handleClose">
        <!-- 内容 -->
        <el-form :inline="true" :model="parameterAddr" class="demo-ruleForm" status-icon label-width="120px" :rules="rules1" ref="argumentForm">
          <el-form-item label="商品参数名称" prop="attribute">
            <el-input v-model.trim="parameterAddr.attribute" placeholder="商品参数名称" />
          </el-form-item>
          <el-form-item label="商品参数值" prop="value">
            <el-input v-model.trim="parameterAddr.value" placeholder="商品参数值" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="parameterEdit() ">确认</el-button>
        </template>
      </el-dialog>
    </div>

    <!-- 规格维度 -->
    <div class="box">
      <h4>规格维度</h4>
      <el-button size="small" type="primary" plain @click="specificationAdd">添加</el-button>

      <!-- 表格 -->
      <el-table :data="addr.specificationList" border style="width: 100%">
        <el-table-column label="维度ID" prop="id" align="center" />
        <el-table-column label="维度名称" prop="title" align="center" />
        <el-table-column label="创建时间" prop="gmtCreate" align="center">
          <template #default="scope">{{new Date().format(scope.row.gmtCreate)}}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" align="center" width="180">
          <template #default="scope">
            <el-button type="primary" @click=" speciEdit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="speciRemove(scope.row, scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 添加对话框 -->
      <el-dialog v-model="specificationVisible" title="创建规格" width="600px" :before-close="handleClose">
        <!-- 内容 -->
        <el-form :inline="true" :model="specificationAddr" class="demo-ruleForm" status-icon label-width="120px" ref="specificationForm" :rules="rules2">
          <el-form-item label="类型名称" prop="title">
            <el-input v-model.trim="specificationAddr.title" placeholder="类型名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="specificationNew() ">确认</el-button>
        </template>
      </el-dialog>

      <!-- 编辑对话框 -->
      <el-dialog v-model="speciEditVisible" title="编辑规格" width="600px" :before-close="handleClose">
        <!-- 内容 -->
        <el-form :inline="true" :model="specificationAddr" class="demo-ruleForm" status-icon label-width="120px" ref="specificationForm" :rules="rules2">
          <el-form-item label="类型名称" prop="title">
            <el-input v-model.trim="specificationAddr.title" placeholder="类型名称" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="specificationEdit() ">确认</el-button>
        </template>
      </el-dialog>
    </div>

    <!-- 商品(Sku)详情-->
    <div class="box">
      <h4>商品(Sku)详情</h4>
      <el-button size="small" type="primary" plain @click="detailsAdd">批量定价</el-button>
      <!-- 标签 -->
      <p>
        <!-- <el-space>
          <el-tag type="warning">颜色</el-tag>
          <el-tag v-for="tag in dynamicTags" :key="tag" class="mx-1" closable :disable-transitions="false" @close="handleDel(tag)">{{ tag }}</el-tag>
          <el-input v-if="inputVisible" ref="InputRef" v-model.trim="inputValue" class="ml-1 w-20" size="small" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
          <el-button v-else size="small" @click="showInput">+ 添加</el-button>
        </el-space>-->

        <el-space v-for="(item,index) in addr.specificationList" :key="item.index" style="width: 100%; padding: 10px 0">
          <el-tag type="warning">{{ item.title }}</el-tag>
          <el-tag v-for="(item2,index2) in item.values" :key="index2" closable @close="handleDel(index,index2)">{{ item2 }}</el-tag>
          <el-input
            v-if="item.inputSkuTagVisible"
            v-model="item.inputSkuTagValue"
            :ref="'input'+index"
            size="small"
            @keydown.enter="handleInputConfirm(item.inputSkuTagValue,index)"
            @blur="handleInputConfirm(item.inputSkuTagValue,index)"
            style="max-width:58.34px"
          />
          <el-button v-else size="small" @click="showInput(index)">+ 添加</el-button>
        </el-space>
      </p>
      <!--商品sku表格详情-->
      <el-table :data="addr.skuList" border style="min-width:800px">
        <el-table-column v-for="(item, index) in addr.specificationList" :label="item.title" :prop="'id_'+item.title" align="center" :key="item.title" />
        <el-table-column prop="name" label="SkuId" align="center" />
        <el-table-column label="￥价格(元)" align="center" width="150px">
          <template #default="scope">
            <el-input-number v-model="scope.row.price" size="small" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="VIP价(元)" align="center" width="150px">
          <template #default="scope">
            <el-input-number v-model="scope.row.vipPrice" size="small" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="￥吊牌价(元)" align="center" width="150px">
          <template #default="scope">
            <el-input-number v-model="scope.row.originalPrice" size="small" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="￥库存(件)" align="center" width="150px">
          <template #default="scope">
            <el-input-number v-model="scope.row.stock" size="small" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="￥重量(克)" align="center" width="150px">
          <template #default="scope">
            <el-input-number v-model="scope.row.weight" size="small" :min="1" />
          </template>
        </el-table-column>
        <el-table-column label="SKU图片" align="center">
          <template #default="scope">
            <el-upload class="avatar-uploader" :action="host+'/upload/admin'" :show-file-list="false" :headers="token" @click="index = scope.$index" :on-success="imgPost">
              <img v-if="scope.row.img" :src="scope.row.img" style="width:100px;height:100px" class="avatar" />
              <el-icon v-else style="width:100px;height:100px">
                <Plus />
              </el-icon>
            </el-upload>
          </template>
        </el-table-column>
        <el-table-column label="条形码" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.barCode" placeholder="请输入条形码" size="small">
              <template #append>
                <el-button size="small" @click="scope.row.barCode=+new Date()">条形码</el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量定价对话框 -->
      <el-dialog v-model="batchVisible" title="批量定价" width="600px" :before-close="handleClose">
        <!-- 内容 -->
        <el-form :inline="true" :model="detailsAddr" class="demo-ruleForm" status-icon label-width="120px">
          <el-form-item label="现价(￥)">
            <el-input-number v-model="detailsAddr.price" :precision="2" :min="1" :max="9999" />
          </el-form-item>
          <el-form-item label="VIP(￥)">
            <el-input-number v-model="detailsAddr.vipPrice" :precision="2" :min="1" :max="9999" />
          </el-form-item>
          <el-form-item label="吊牌价(￥)">
            <el-input-number v-model="detailsAddr.originalPrice" :precision="2" :min="1" :max="9999" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="detailsNew() ">确认</el-button>
        </template>
      </el-dialog>
    </div>

    <!-- 操作 -->
    <div style="flex: auto;margin-top: 20px;">
      <el-button @click="cancelClick">取消</el-button>
      <el-button type="primary" @click="addnew()">保存商品</el-button>
    </div>
  </div>
</template>

<script>
import { post, host } from '@/utils/http.js' // 引入封装工具
import jsCookie from "js-cookie";
import { Plus } from '@element-plus/icons-vue'//引入图标
//富文本
// import '@wangeditor/editor/dist/css/style.css'; // 引入 css
// import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue';
// import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import RichText from "@/components/richtext/RichText.vue";
import { mapActions } from "vuex";
import { ElMessage } from 'element-plus';


export default {
  components: { Plus, RichText },
  // setup() {
  //   // 编辑器实例，必须用 shallowRef
  //   const editorRef = shallowRef()  //获取工具栏

  //   // 内容 HTML
  //   const valueHtml = ref('<p>hello</p>')
  //   // 模拟 ajax 异步获取内容
  //   onMounted(() => {
  //     setTimeout(() => {
  //       valueHtml.value = '<p>商品详情介绍</p>'
  //     }, 1500)
  //   })
  //   const toolbarConfig = {} //工具栏配置
  //   const editorConfig = {
  //     placeholder: '请输入内容...',
  //     MENU_CONF: {}
  //   }// 编辑器配置
  //   editorConfig.hoverbarKeys = {}//编辑器悬停
  //   // 自定义校验图片
  //   function customCheckImageFn(src, alt, url) {
  //     if (!src) {
  //       return
  //     }
  //     if (src.indexOf('http') !== 0) {
  //       return '图片网址必须以 http/https 开头'
  //     }
  //     return true
  //     // 返回值有三种选择：
  //     // 1. 返回 true ，说明检查通过，编辑器将正常插入图片
  //     // 2. 返回一个字符串，说明检查未通过，编辑器会阻止插入。会 alert 出错误信息（即返回的字符串）
  //     // 3. 返回 undefined（即没有任何返回），说明检查未通过，编辑器会阻止插入。但不会提示任何信息
  //   }

  //   // 转换图片链接
  //   function customParseImageSrc(src) {
  //     if (src.indexOf('http') !== 0) {
  //       return `http://${src}`
  //     }
  //     return src
  //   }
  //   // 插入图片
  //   editorConfig.MENU_CONF['insertImage'] = {
  //     onInsertedImage(imageNode) {
  //       if (imageNode == null) return

  //       const { src, alt, url, href } = imageNode
  //     },
  //     checkImage: customCheckImageFn, // 也支持 async 函数
  //     parseImageSrc: customParseImageSrc, // 也支持 async 函数
  //   }
  //   // 编辑图片
  //   editorConfig.MENU_CONF['editImage'] = {
  //     onUpdatedImage(imageNode) {

  //       if (imageNode == null) return

  //       const { src, alt, url } = imageNode
  //     },
  //     checkImage: customCheckImageFn, // 也支持 async 函数
  //     parseImageSrc: customParseImageSrc, // 也支持 async 函数
  //   }
  //   // 修改 uploadImage 菜单配置
  //   editorConfig.MENU_CONF['uploadImage'] = {
  //     // 自定义上传
  //     async customUpload(file, insertFn) {
  //       // file 即选中的文件
  //       let formDatas = new FormData();
  //       formDatas.append("file", file);
  //       let { name, type } = file
  //       uploadImage("http://192.168.1.188:8080/upload/admin", formDatas).then(res => {
  //         if (200 == res.data.errno) {
  //           ElMessage.success("上传成功");
  //           let alt = name
  //           let href = type
  //           let { url } = res.data
  //           // 自己实现上传，并得到图片 url alt href
  //           // 最后插入图片
  //           insertFn(url, alt, href)
  //         } else { ElMessage.error("上传失败"); }
  //       })
  //     },
  //   }
  //   // 组件销毁时，也及时销毁编辑器
  //   onBeforeUnmount(() => {
  //     const editor = editorRef.value
  //     if (editor == null) return
  //     editor.destroy()
  //   })
  //   // EXTEND_CONF
  //   // 用于第三方插件做扩展配置，如 mention 插件。
  //   const handleCreated = (editor) => {//创建完毕的回调函数
  //     editorRef.value = editor // 记录 editor 实例，重要！
  //   }
  //   return {
  //     editorRef,
  //     valueHtml,
  //     mode: 'default', // 或 'simple'
  //     toolbarConfig,
  //     editorConfig,
  //     handleCreated
  //   }
  // },
  setup() {
    return { host }
  },
  data() {
    return {

      token: {},
      addr: {
        title: '',//商品名称
        price: '', // 原始价格
        originalPrice: "",//当前价格
        vipPrice: "",//VIP价格
        freightTemplateId: "",//运费模板id
        status: 1,//运费模板
        imgList: [],//上传图片
        img: '',//广告图片
        unit: '',//商品单位
        categoryId: '',//所属类目
        description: '',//商品单位
        detail: "",//商品详细介绍
        stock: 0,
        specificationList: [],//规格
        attributeList: [],
        skuList: [],//商品数据表格
      },
      //   表单验证
      rules: {
        vipPrice: [{ message: "vip价格不能为空", required: true, }],
        title: [{ message: "商品名称不能为空", required: true, }],
        originalPrice: [{ message: "原始价格不能为空", required: true, }],
        price: [{ message: "当前价格不能为空", required: true, }],
        freightTemplateId: [{ message: "运费模板不能为空", required: true, }],
        categoryId: [{ message: "类目不能为空", required: true, }],
        unit: [{ message: "商品单位不能为空", required: true, }],
        status: [{ message: "是否在售不能为空", required: true, }],
        detail: [{ message: "商品详细介绍不能为空", required: true, }],
      },
      //   商品参数表单验证
      rules1: {
        attribute: [{ message: "商品参数名称不能为空", required: true, }],
        value: [{ message: "商品参数值不能为空", required: true, }],
      },
      //   规格维度表单验证
      rules2: {
        title: [{ message: "类型名称不能为空", required: true, }],
      },
      //  地区选择
      freightOptions: [],
      //类目数据
      typeData: [],
      // Cascader 级联选择器配置信息
      props: {
        value: "id",
        label: "title",
        children: "childrenList",
        emitPath: false
      },
      // 商品参数弹框数据
      parameterAddr: {
        attribute: '',//参数名称
        value: '',//参数值
      },
      //   下标
      index: -1,
      dialogVisible: false,//商品参数显示/隐藏
      EditVisible: false,//编辑商品参数显示/隐藏


      // 规格弹框数据
      specificationAddr: {
        title: ''
      },
      specificationVisible: false,//规格显示/隐藏
      speciEditVisible: false,//规格编辑显示/隐藏
      // 商品详情弹框数据
      detailsAddr: {
        price: 1,//现价
        vipPrice: 1,//VIP价格
        originalPrice: 1,//吊牌价
      },
      detailsVisible: false,//详情显示/隐藏
      batchVisible: false,//批量定价显示/隐藏

      // 标签
      inputValue: '',
      dynamicTags: [],
      inputVisible: false,

      id: ''
    }

  },
  created() {
    this.tokens()// 图片token
    this.getSpuBigTrees() //调用类目
    this.getFreight()
    let id = this.$route.query.id
    if (!id) {
      let index = this.$store.state.tags.tagList.findIndex(item => item.path == this.$route.path)
      this.delTag(index)
    } else {
      this.id = id
      this.initData(id)
    }

  },
  activated() {
    console.log("生效");
    let id = this.$route.query.id
    if (id !== this.id) {
      this.id = id
      this.initData(id)
    }
  },
  deactivated() {
    console.log("失效");
  },
  methods: {
    ...mapActions(["delTag"]),
    // 富文本获取内容改变获取
    // handleChange(editor) {
    //   this.addr.detail = editor.getHtml()
    // },

    // 图片token
    tokens() {
      this.token = { ADMINTOKEN: jsCookie.get("token") }
    },
    // 初始化编辑数据
    initData(id) {
      if (!id) return
      let formData = {
        _gp: "product",
        _mt: "getProduct",
        spuId: id
      }
      post(formData).then((res) => {
        if (res) {
          // console.log(res);
          let { data } = res.data
          data.specificationList.forEach(item => {
            item.values = []
            item.inputSkuTagValue = ""
            data.skuList.forEach(item1 => {
              item1.specification.split(",").forEach(item2 => {
                let index = item2.indexOf("_")
                let value = item2.slice(index + 1, item.length)//value
                let title = item2.slice(0, index)//title
                if (item.title == title && !item.values.find(item3 => item3 === value)) {
                  item.values.push(value)
                }
              })
            })
          })
          Object.assign(this.addr, data)
          this.addr.imgList = data.imgList.map(item => { return { url: item } })
          this.valueHtml = data.detail
          this.createSkuTable()
          this.addr.skuList.forEach((item, index) => {
            Object.assign(item, data.skuList[index])
          })
        }
      });
    },
    // 获取运费模板
    getFreight() {
      post({ _gp: "admin.freight", _mt: "list" }).then(res => this.freightOptions = res.data.data)
    },
    // 类目
    getSpuBigTrees() {
      let data = {
        _gp: "admin.category",
        _mt: "categoryTree",
      }
      post(data).then(res => {
        let { data } = res.data
        this.typeData = data
      })
    },

    // 图片
    handleAvatarSuccess(response, v) {
      console.log(response, v);
      if (200 == response.errno) {
        ElMessage.success("添加成功")
        // this.addr.imgList.push(response.url);
        // this.addr.img = this.addr.imgList[0]
        // this.addr.imgList.push(v);
        this.addr.img = this.addr.imgList[0]?.response?.url || this.addr.imgList[0].url
      }
    },

    // 表格上传图片
    imgPost(res) {
      let { errno, url } = res
      if (200 == errno) {
        this.addr.skuList[this.index].img = url
      }
    },

    // 商品参数添加弹窗
    parameterAdd() {
      this.dialogVisible = true
      this.parameterAddr.attribute = ''
      this.parameterAddr.value = ''

    },
    // 商品参数编辑弹框
    tableEdit(row) {
      this.EditVisible = true
      Object.assign(this.parameterAddr, row)

    },
    // 商品参数提交
    parameterNew() {
      this.$refs.argumentForm.validate((valid) => {
        if (!valid) return
        this.dialogVisible = false
        let { attribute, value } = this.parameterAddr
        let index = this.addr.attributeList.findIndex(item => item.attribute === attribute) //查找是否重复
        if (index == -1) {
          this.addr.attributeList.push({ attribute, value })
        } else {
          ElMessage.error("不能添加重复数据")
        }
      });
    },
    // 商品参数编辑
    parameterEdit() {
      this.$refs.argumentForm.validate((valid) => {
        if (!valid) return
        let { attribute, value } = this.parameterAddr
        this.addr.attributeList.splice(this.index, 1, { attribute, value }) //替换  
        this.EditVisible = false
      });

    },
    // 数据删除
    tableRemove(row, index) {
      let name = row.attribute ?? row.title
      ElMessageBox.confirm(`您确定要删除商品参数'${name}' 吗?`, '警告', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }).then(() => {
        this.addr.attributeList.splice(index, 1)
        this.createSkuTable()
      }).catch(() => { })
    },

    // 规格添加弹窗
    specificationAdd() {
      this.specificationVisible = true
      this.specificationAddr.title = ""
    },
    // 规格添加提交
    specificationNew() {
      this.$refs.specificationForm.validate((valid) => {
        if (!valid) return
        let { title } = this.specificationAddr
        let data = { title, values: [], gmtCreate: +new Date(), gmtUpdate: +new Date(), inputSkuTagValue: '', inputSkuTagVisible: false }//要插入的数据s
        let index = this.addr.specificationList.findIndex(item => item.title === title)//查找是否有重复
        if (index == -1) {
          this.addr.specificationList.push(data) //直接加进去
          this.createSkuTable()
        } else {
          ElMessage.error("不能添加重复数据")
        }
        this.specificationVisible = false
      });
    },

    // 规格编辑弹窗
    speciEdit(row) {
      this.speciEditVisible = true
      Object.assign(this.specificationAddr, row)

    },
    // 规格编辑提交
    specificationEdit() {
      this.$refs.specificationForm.validate((valid) => {
        if (!valid) return
        let { title } = this.specificationAddr
        let data = { title, values: [], gmtCreate: +new Date(), gmtUpdate: +new Date(), inputSkuTagValue: '', inputSkuTagVisible: false }
        this.addr.specificationList.splice(this.index, 1, data) //替换  
        this.createSkuTable()
        this.speciEditVisible = false
      });
    },
    speciRemove(row, index) {
      let name = row.title
      ElMessageBox.confirm(`您确定要删除商品参数'${name}' 吗?`, '警告', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }).then(() => {
        this.addr.specificationList.splice(index, 1)
        this.createSkuTable()
      }).catch(() => { })
    },
    // 批量定价弹窗
    detailsAdd() {
      this.batchVisible = true

    },
    // 批量定价提交
    detailsNew() {
      let { price, vipPrice, originalPrice } = this.detailsAddr
      if (this.addr.skuList.length == 0 || this.addr.specificationList[0].values.length == 0) return ElMessage.error("没有数据,无法更改")
      this.addr.skuList.forEach(item => {
        item.price = price
        item.vipPrice = vipPrice
        item.originalPrice = originalPrice
      })
      // 循环结束之后关闭
      this.batchVisible = false
    },

    // 生成sku表格
    createSkuTable() {
      const specList = this.addr.specificationList//规格总数据
      const valueList = specList.map(item => item.values).filter(item => item.length > 0)//规格value
      const titles = specList.filter(item => item.values.length > 0).map(item => item.title)//规格title
      // 笛卡尔积直接累计数据
      var skuList = valueList.reduce((totle, item) => {
        var array = []
        totle.forEach(item2 => {
          item.forEach(item3 => {
            array.push(item2.concat([item3]))
          })
        })
        return array
      }, [[]])
      if (0 === valueList.length) {
        skuList = [];
      }
      // 构建sku表格数据
      var skuTable = skuList.map(item => {
        let obj = {
          price: 0,//现价
          vipPrice: 0,//vip价格
          originalPrice: 0,//吊牌价
          stock: 0,//库存
          barCode: "",//随机数
          weight: 1,//重量
          img: "",//图片
          title: [],//标题
          specification: []//标题描述
        }
        item.forEach((val, index) => {
          var key = "id_" + titles[index]
          obj[key] = val;
          obj.title.push(val);
          obj.specification.push(titles[index] + "_" + val)
        })
        obj.title = obj.title.join()
        obj.specification = obj.specification.join()
        return obj
      })
      this.addr.skuList = skuTable
    },

    // 标签
    showInput(index) {
      // this.inputVisible = true
      this.addr.specificationList[index].inputSkuTagVisible = true // 按钮切换为input输入框
      this.$nextTick(() => this.$refs['input' + index][0].focus()) //获取焦点
    },
    handleDel(index, index2) {
      // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
      this.addr.specificationList[index].values.splice(index2, 1)
      this.createSkuTable()
    },
    handleInputConfirm(val, index) {
      // if (this.inputValue) {
      //   this.dynamicTags.push(this.inputValue)
      // }
      // this.inputVisible = false
      // this.inputValue = ''

      let specificationList = this.addr.specificationList
      if (val) {//如果添加的信息不为空
        let i = specificationList[index].values.findIndex(item => item === val)
        if (i == -1) {
          this.addr.specificationList[index].values.push(val)
          this.createSkuTable()
        } else {
          ElMessage.error("不能添加重复数据")
        }
      }
      this.addr.specificationList[index].inputSkuTagVisible = false //关闭显示
      this.addr.specificationList[index].inputSkuTagValue = '' //并且清空输入内容

    },

    // 全部编辑提交
    addnew() {
      this.$refs.addr.validate((valid) => {
        if (!valid) return
        if (this.addr.attributeList.length == 0) return ElMessage.error("商品参数不能为空")
        if (this.addr.specificationList.length == 0) return ElMessage.error("商品规格不能为空")
        if (this.addr.skuList.length == 0) return ElMessage.error("商品信息不能为空")
        let addrs = JSON.parse(JSON.stringify(this.addr))
        addrs.imgList = addrs.imgList.map(item => item?.response?.url || item.url)
        console.log(addrs.imgList);
        let addr = {
          _gp: "admin.product",
          _mt: "edit",
          spuDTO: JSON.stringify(addrs)
        }
        post(addr).then(res => {
          console.log(res);
          if (res) {
            ElMessage.success("编辑成功！")
            ElMessageBox.confirm('编辑成功?是否继续编辑', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', }).then(() => {
              // this.addr = {}
            }).catch(() => {
              this.$router.push({ path: "/bcommodity/List" })
            })

          }
        })
      });
    },
    // 取消
    cancelClick() {
      console.log("取消");
      let index = this.$store.state.tags.tagList.findIndex(item => item.path == this.$route.path)
      this.delTag(index)
      console.log(index);
    },

    // 关闭弹框
    handleClose() {
      ElMessage({
        type: 'info',
        message: '取消操作！'
      })
      this.dialogVisible = false
      this.EditVisible = false

      this.specificationVisible = false
      this.speciEditVisible = false


      this.detailsVisible = false
      this.batchVisible = false
    },
    // 取消弹框按钮
    resetForm() {
      ElMessage({
        type: 'info',
        message: '取消操作！'
      })
      this.dialogVisible = false
      this.EditVisible = false

      this.specificationVisible = false
      this.speciEditVisible = false

      this.detailsVisible = false
      this.batchVisible = false

    },
  }
}
</script>

<style lang="less" scoped>
// 盒子阴影
.box {
  width: 98%;
  padding: 15px;
  box-shadow: 0px 0px 15px 5px #ccc;
}
</style>